package com.chj.comp.common.core.util;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;

/**
 * @author cuihui
 * @date 2022/01/16
 */
public class PageParam<T> extends Page<T> {

	/**
	 * 字段-页数
	 */
	private static final String PAGE = "page";

	/**
	 * 字段-每页条数
	 */
	private static final String SIZE = "size";

	/**
	 * 字段-排序字段(仅支持单个)
	 */
	private static final String ORDER = "order";

	/**
	 * 字段-排序方式(仅支持单个)
	 */
	private static final String IS_ASC = "isAsc";

	/**
	 * 当前页(与传参保持统一)
	 */
	protected long page;

	/**
	 * 前台传参
	 */
	@Getter
	@Setter
	private Map<String, Object> condition;

	public PageParam(Map<String, Object> condition) {
		super(Integer.parseInt(condition.getOrDefault(PAGE, 1).toString()),
			  Integer.parseInt(condition.getOrDefault(SIZE, 10).toString()));

		String orderByField = condition.getOrDefault(ORDER, "").toString();
		Boolean isAsc = Boolean.parseBoolean(condition.getOrDefault(IS_ASC, Boolean.TRUE).toString());
		if (StringUtils.isNotEmpty(orderByField)) {
			OrderItem orderItem = new OrderItem();
			orderItem.setColumn(orderByField);
			orderItem.setAsc(isAsc);
			this.addOrder(orderItem);
		}
		condition.remove(PAGE);
		condition.remove(SIZE);
		condition.remove(ORDER);
		condition.remove(IS_ASC);
		this.condition = condition;
	}

	/**
	 * 当前页
	 */
	public long getPage() {
		return this.current;
	}
}
